package monster.com.cvh.adapter;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.util.List;

import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import monster.com.cvh.R;
import monster.com.cvh.activity.LoginActivity;
import monster.com.cvh.bean.CommentDetailsBean;
import monster.com.cvh.bean.MessageEvent;
import monster.com.cvh.bean.PostBean;
import monster.com.cvh.bean.PublishCommentBean;
import monster.com.cvh.util.EditTextDialog;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.util.TimeConvert;
import monster.com.cvh.util.TimeUtil;
import okhttp3.Call;
import okhttp3.Response;

import static monster.com.cvh.util.ToastUtils.showToastLong;

/**
 * @author: monster
 * @data: 2018/4/3
 * @function: 评论详情adapter
 */
public class CommentDetailsAdapter extends BaseQuickAdapter<CommentDetailsBean.DataBean, BaseViewHolder> {
    private String lastTime;
    private boolean is_praise;
    private CommentMoreAdapter commentMoreAdapter;
    private List<CommentDetailsBean.DataBean.SubCommentsBean> sub_comments;
    private FragmentManager fragmentManager;
    private BaseBottomDialog mDialog;
    private String user_name;
    private ProgressDialog mDialogLoging;

    public CommentDetailsAdapter(int layoutResId, @Nullable List<CommentDetailsBean.DataBean> data, FragmentManager fragmentManager) {
        super(layoutResId, data);
        this.fragmentManager = fragmentManager;
    }

    @Override
    protected void convert(final BaseViewHolder helper, final CommentDetailsBean.DataBean item) {
        mDialogLoging = new ProgressDialog(mContext);
        mDialogLoging.setMessage(mContext.getResources().getString(R.string.wait));
        mDialogLoging.setOnKeyListener(new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                //回退键监听
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                }
                return false;
            }
        });
        mDialogLoging.setCanceledOnTouchOutside(false);
        //获取当前时间戳
        long timeStamp = System.currentTimeMillis() / 1000;
        try {
            String s = TimeConvert.dateToStamp(item.getPublish_time());
            long articleTime = timeStamp - Long.valueOf(s) / 1000;
            lastTime = TimeUtil.calculateTime(articleTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        helper.addOnClickListener(R.id.tv_item_comment_detals_reply);
        Glide.with(mContext).load(item.getIcon_url()).into((ImageView) helper.getView(R.id.iv_item_comment_details_avatar));
        helper.setText(R.id.tv_item_comment_time, lastTime);
        helper.setText(R.id.tv_item_comment_details, item.getUser_name());
        helper.setText(R.id.tv_item_comment_text, item.getContent());
        LinearLayout mLlPraise = helper.getView(R.id.ll_item_comment_details);
        helper.setText(R.id.tv_item_comment_details_priase,item.getPraise_count()+"");
        //获取列表的列表
        RecyclerView mRvItemCommentDetails = helper.getView(R.id.recyclerview_item_comment_details);
        sub_comments = item.getSub_comments();

        if (sub_comments !=null && sub_comments.size() >0){
            mRvItemCommentDetails.setBackgroundResource(R.drawable.po);
        }else {
            mRvItemCommentDetails.setBackgroundColor(Color.WHITE);
        }
        mRvItemCommentDetails.setLayoutManager(new LinearLayoutManager(mContext));
        commentMoreAdapter = new CommentMoreAdapter(R.layout.item_comment_more, sub_comments,fragmentManager);
        mRvItemCommentDetails.setAdapter(commentMoreAdapter);
        mRvItemCommentDetails.setNestedScrollingEnabled(false);


//        deleteComment();
        /**
         * 发布评论
         */
        commentMoreAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, final int position) {
                if (SPUtils.getString(mContext,"token","") ==null || SPUtils.getString(mContext,"token","").equals("")){
                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
                }else {
                    Log.i(TAG, "onItemClick: " + item.getSub_comments().get(position).getId());
                    EditTextDialog dialog = new EditTextDialog();
                    int layoutRes = dialog.getLayoutRes();
                    mDialog = BottomDialog.create(fragmentManager)
                            .setViewListener(new BottomDialog.ViewListener() {
                                @Override
                                public void bindView(View v) {
                                    final EditText commentContext = v.findViewById(R.id.edt_dialog_comment_context);
                                    sub_comments = item.getSub_comments();
                                    user_name = sub_comments.get(position).getUser_name();
                                    commentContext.setHint("回复@" + user_name);
                                    //取消按钮
                                    v.findViewById(R.id.btn_dialog_comment_cancel).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            mDialog.dismiss();
                                        }
                                    });
                                    /**
                                     //         * 确定按钮
                                     //         */
                                    v.findViewById(R.id.btn_dialog_comment_confirm).setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            mDialogLoging.show();
                                            if (commentContext.getText().toString().trim().equals("")) {
                                                showToastLong("请输入内容");
                                            } else {
                                                OkGo.<String>post(MyConstant.CREATE_COMMENT).params("comment_id", item.getSub_comments().get(position).getId()).params("token", SPUtils.getString(mContext, "token", ""))
                                                        .params("content", commentContext.getText().toString().trim()).execute(new StringCallback() {
                                                    @Override
                                                    public void onSuccess(String s, Call call, Response response) {
                                                        Gson gson = new Gson();
                                                        PublishCommentBean publishCommentBean = gson.fromJson(s, PublishCommentBean.class);
                                                        switch (publishCommentBean.getCode()) {
                                                            case 1:
//                                                      reSetComment();
                                                                //发布成功
//                                                        helper.setText(R.id.item_comment_more_second_user,item.getUser_name());
                                                                showToastLong("发布成功");
                                                                EventBus.getDefault().post(new MessageEvent("adapter通知我更新ui了"));
                                                                mDialogLoging.dismiss();
                                                                mDialog.dismiss();
                                                                break;
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    });

                                }
                            })
                            .setLayoutRes(layoutRes)
                            .setDimAmount(0.1f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                            .setTag("BottomDialog")     // setting the DialogFragment tag
                            .show();
                }
            }
        });




        final ImageView mIvPraise = helper.getView(R.id.iv_item_comment_priase);
        is_praise = item.isIs_praise();
        helper.addOnClickListener(R.id.tv_item_comment_delete);
        TextView deletComment = helper.getView(R.id.tv_item_comment_delete);
        if (String.valueOf(item.getUser_id()).equals(SPUtils.getInt(mContext,"id",-1)) ){
            mLlPraise.setVisibility(View.GONE);
            deletComment.setVisibility(View.VISIBLE);
        }else {
            deletComment.setVisibility(View.GONE);
            mLlPraise.setVisibility(View.VISIBLE);
            if (is_praise){
                //已经点赞
                mIvPraise.setImageResource(R.mipmap.information_praise_after);
                mIvPraise.setEnabled(false);
            }else {
                //未点赞
                mIvPraise.setImageResource(R.mipmap.information_praise_before);
                mIvPraise.setEnabled(true);
                /**
                 * 点赞请求
                 */
                mLlPraise.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (SPUtils.getString(mContext,"token","") == null || SPUtils.getString(mContext,"token","").equals("")){
                            mContext.startActivity(new Intent(mContext,LoginActivity.class));
                        }else {
                            final int addPraise = item.getPraise_count() + 1;
                            Log.i(TAG, "onClick: " + addPraise + "position:" + helper.getLayoutPosition());
                            OkGo.<String>post(MyConstant.MAKE_PRAISE).params("token", SPUtils.getString(mContext, "token", ""))
                                    .params("is_praise", true).params("comment_id", item.getId()).execute(new StringCallback() {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    Gson gosn = new Gson();
                                    PostBean bean = gosn.fromJson(s, PostBean.class);
                                    if (bean.getCode() == 1) {
                                        mIvPraise.setImageResource(R.mipmap.information_praise_after);
                                        mIvPraise.setEnabled(false);
                                        helper.setText(R.id.tv_item_comment_details_priase, addPraise + "");
                                    }

                                }
                            });
                        }
                    }
                });
            }
        }
    }
}
